/**
 * 作者: 傅卿何
 * QQ: 3620060826
 * 插件库: https://gitee.com/Tloml-Starry/Plugin-Example
 */


import fetch from 'node-fetch'
import common from '../../lib/common/common.js'

export class example extends plugin {
    constructor() {
        super({
            name: "鸣潮卡池多久未复刻查询",
            dsc: "鸣潮卡池多久未复刻查询",
            event: "message",
            priority: 1,
            rule: [
                { reg: /^(mc|鸣潮)卡池多久未复刻$/, fnc: 'queryUpDate' }
            ]
        })
    }
    async queryUpDate(e) {
        const linkData = await (await fetch('https://raw.gitcode.com/Kevin1217/resources/raw/master/resources/json/kuro/mc卡池记录.json')).json()

        let { CurrentRole, OtherRoles } = linkData

        for (const name of CurrentRole) {
            OtherRoles = OtherRoles.filter(obj => obj['name'] !== name)
        }

        const result = obtain_interval_time(OtherRoles)
        const currentUP = `当前唤取: ${CurrentRole}`

        return e.reply(await common.makeForwardMsg(e, [currentUP, ...result], currentUP))
    }
}

function obtain_interval_time(linkData) {
    const today = new Date();

    let result = [];
    for (const data of linkData) {
        const { name, picID, Record } = data
        const ReplicationNumber = Record.length
        const lastReplicationRecord = Record[ReplicationNumber - 1];
        const { StartTime, EndTime, Version, UpOrDown } = lastReplicationRecord
        const timeDiff = today.getTime() - new Date(lastReplicationRecord['EndTime']).getTime();
        const daysNumber = Math.floor(timeDiff / (1000 * 60 * 60 * 24)).toString().padStart(3, '0');

        result.push([
            segment.image(`https://prod-alicdn-community.kurobbs.com/forum/${picID}.png`),
            `${name} 已 [${daysNumber}]天未复刻\r`,
            `最后UP时间: ${Number.isInteger(Version) ? `${Version}.0` : Version}${UpOrDown}半\r`,
            `${StartTime} - ${EndTime}\r`,
            `UP次数: ${ReplicationNumber}`
        ])
    }

    result.sort((a, b) => {
        if (typeof b === 'string' && typeof a === 'string') {
            const daysA = parseInt(a.match(/\[(\d+)\]/)[1]);
            const daysB = parseInt(b.match(/\[(\d+)\]/)[1]);
            return daysB - daysA;
        } else {
            return '?';
        }
    });
    return result;
}
